import log from "./logger";
import * as mssql from "mssql";
import {NodeCO, TrainAllCO} from "./interface";
import config from "./config";
import sender from "./sender";

function getTime(dateString: string) {
    // 创建一个新的 Date 对象
    let date = new Date(dateString.trim());
    // 获取年、月、日
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // getMonth() 返回 0-11，表示1-12月，所以需要+1
    let day = date.getDate();
    // 将月份和日期格式化为两位数
    let month2 = month.toString().padStart(2, '0');
    let day2 = day.toString().padStart(2, '0');
    // 构建新的日期字符串
    return `${year}-${month2}-${day2}`;
}

// 正则表达式匹配类似2024-4-8的日期格式
const dateRegex = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;

// 将日期转换为标准格式YYYY-MM-DD
function formatDate(dateString: string) {
    if (dateString) {
        dateString = dateString.trim()
        const match = dateString.match(dateRegex);
        if (match) {
            const year = match[1];
            const month = match[2].padStart(2, '0'); // 确保月份有两位数字
            const day = match[3].padStart(2, '0'); // 确保日期有两位数字
            return `${year}-${month}-${day}`;
        }
    }
    return null;
}

function formatCurrDate() {
    const now = new Date();
    const year = now.getFullYear();
    // getMonth() 返回的月份是从 0 开始计数的，所以要加 1
    const month = now.getMonth() + 1;
    return `${year}-${month}`;
}

class WltlgTrainWorker {
    init() {
        this.collection().catch((e) => {
            log.info(e);
        });
        setInterval(() => {
            this.collection().catch((e) => {
                log.info(e);
            });
        }, 1000 * 60 * 2)
    }

    async collection() {
        const cfg = {
            user: 'hlsk',
            password: 'hlsk1234',
            server: '192.168.1.38',
            database: '装车',
            port: 1433,
            options: {
                encrypt: false,
                tdsVersion: '7_1'
            }
        };
        await mssql.connect(cfg);
        try {
            let currDate = formatCurrDate();
            log.info("当前日期：" + currDate);
            let sql = 'SELECT TOP 15 [列车编号] as code\n' +
                '      ,[装车时间] as time\n' +
                '      ,[车厢数] as totalNode\n' +
                '      ,[列车载重] as totalMaxWeight\n' +
                '      ,[列车实装] as totalWeight\n' +
                '      ,[装车误差] as totalDiffWeight\n' +
                '      ,[到站] as stationName\n' +
                '      ,[收货单位] as senderName\n' +
                '      ,[煤种] as productName\n' +
                "  FROM [装车].[dbo].[列车编组] where 装车时间 like '" + currDate + "%' order by 装车时间 desc"
            const res = await new mssql.Request().query(sql);
            if (res.recordset.length <= 0) {
                return;
            }
            // console.log(res.recordset)
            // 转换记录中的日期格式
            res.recordset.forEach(record => {
                record.formattedDate = formatDate(record.time);
            });
            // 按日期排序，最新的在前
            // @ts-ignore
            res.recordset.sort((a, b) => new Date(b.formattedDate) - new Date(a.formattedDate));
            // 获取最新的2条记录
            const latestRecords = res.recordset.slice(0, 6);
            // console.log(latestRecords)
            for (let data of latestRecords) {
                log.info(data);
                const nodes: NodeCO[] = []
                let code = data['code']
                let time = getTime(data['time']);
                let sql2 = 'SELECT TOP 1000 [序号] as sort\n' +
                    '      ,[车型] as carType\n' +
                    '      ,[车号] as no\n' +
                    '      ,[载重] as maxNetWeight\n' +
                    '      ,[实装] as weight\n' +
                    '      ,[误差] as diffWeight\n' +
                    '      ,[装厢时间] as time\n' +
                    '  FROM [装车].[dbo].[装车记录] WHERE [列车编号] = \'' + code + '\''
                const res2 = await new mssql.Request().query(sql2);
                if (res2.recordset.length <= 0) {
                    return
                }
                for (let i = 0; i < res2.recordset.length; i++) {
                    let data2 = res2.recordset[i]
                    nodes.push({
                        centerDeviation: "",
                        frontBackDiff: "",
                        diffWeight: Number.parseFloat(data2['diffWeight']) / 1000,
                        code: code + '-' + data2['no'],
                        lable: null,
                        maxNetWeight: Number.parseFloat(data2['maxNetWeight']) / 1000,
                        no: data2['no'],
                        sort: data2['sort'],
                        speed: null,
                        standardTareWeight: null,
                        time: time + ' ' + data2['time'],
                        trainCode: code,
                        carType: data2['carType'],
                        weight: Number.parseFloat(data2['weight']) / 1000,
                        containerNumber1: null,
                        containerNumber2: null,
                        containerType1: null,
                        containerType2: null,
                        state: 'Done',
                        createTenantId: null,
                        createTenantName: null
                    })
                }
                log.info("nodes[0]:", nodes[0]);
                let train: TrainAllCO = {
                    wagonType: "Gondola",
                    firstNo: nodes[0].no,
                    lastNo: nodes[nodes.length - 1].no,
                    type: "db",
                    totalDiffWeight: Number.parseFloat(data['totalDiffWeight']) / 1000,
                    totalMaxWeight: Number.parseFloat(data['totalMaxWeight']) / 1000,
                    totalWeight: Number.parseFloat(data['totalWeight']) / 1000,
                    boxCount: null,
                    code: code,
                    deviceName: config.deviceName,
                    direction: "Leave",
                    name: code,
                    no: code,
                    nodes: nodes,
                    platformId: config.platformId,
                    platformName: config.platformName,
                    productName: data['productName'],
                    senderName: data['senderName'],
                    startTime: nodes[0]['time'],
                    endTime: nodes[nodes.length - 1]['time'],
                    stationName: data['stationName'],
                    time: time + ' 00:00:00',
                    createTenantId: null,
                    createTenantName: null,
                    totalNode: nodes.length
                }
                try {
                    await sender.send("trainAll", train);
                } catch (e) {
                    log.error("err train:", train);
                }
            }
        } catch (e) {
            log.error(e);
        }
    }
}

const wltlgTrainWorker = new WltlgTrainWorker();
export default wltlgTrainWorker;